package cn.lopr.hfbdqn.configuration;


import cn.lopr.hfbdqn.annotaion.Auth;
import cn.lopr.hfbdqn.common.Result;
import cn.lopr.hfbdqn.pojo.User;
import cn.lopr.hfbdqn.service.UserService;
import cn.lopr.hfbdqn.util.jwt.JwtUtil;
import cn.lopr.mvc.frame.HandlerInterceptorAdapter;
import cn.lopr.mvc.frame.annotaion.Autowired;
import cn.lopr.mvc.frame.annotaion.Component;
import cn.lopr.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * 权限拦截
 *
 * @author shuangyang7
 * @date 2021/5/30 11:47
 */
@Component
public class Interceptor implements HandlerInterceptorAdapter {
    @Autowired
    UserService userService;
    ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    JwtUtil jwtUtil;

    @Override
    public boolean preHandler(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        Method method = (Method) handler;
        if (!method.isAnnotationPresent(Auth.class)) {
            return true;
        }
        String authorization = request.getParameter("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            Result<?> result = new Result<>(Result.NEED_LOGIN, "请先登录");
            response.getWriter().write(objectMapper.writeValueAsString(result));
            return false;
        }

        Claims claims = null;
        try {
            claims = jwtUtil.parseJWT(authorization);
        } catch (ExpiredJwtException e) {
            Result<?> result = new Result<>(Result.NEED_LOGIN, "您的登录已经过期");
            response.getWriter().write(objectMapper.writeValueAsString(result));
            return false;
        }

        String id = claims.getId();
        User userById = userService.getUserById(Integer.valueOf(id));

        if (userById == null) {
            Result<?> result = new Result<>(Result.NEED_LOGIN);
            response.getWriter().write(objectMapper.writeValueAsString(result));
            return false;
        }

        AuthInfo.set(userById);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler) {
        AuthInfo.remove();
    }
}
